package com.taichuan.selfcheck.ui.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.taichuan.keysupport.Key;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.hardware.audio.MediaRecordClient;
import com.taichuan.selfcheck.mvp.presenter.TestAudioPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.TestAudioInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.selfcheck.ui.view.audio.VUMeter;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2021/3/24
 */
public class TestAudioFragment extends AppBaseFragment<TestAudioInterface, TestAudioPresenter> implements TestAudioInterface {
    private static final String TAG = TestAudioFragment.class.getSimpleName();

    /**
     * 定义一组Handler事件： 刷新录音计时器时间
     */
    private static final int MSG_REFRESH_RECORD_TIMER_TIME = 1;
    /**
     * 定义一组Handler事件： 刷新播放计时器时间
     */
    private static final int MSG_REFRESH_PLAY_TIMER_TIME = 2;

    /**
     * 计时器更新频率
     */
    private static final int REFRESH_DELAY_TIME = 1 * 1000;

    private static final int CURRENT_RUN_BUTTON_ID_NONE = -1;

    /**
     * 计时器格式
     */
    private static final String timerFormat = "%02d:%02d";

    @BindView(R.id.record_timer_textView)
    TextView recordTimerTv;
    @BindView(R.id.record_timer_icon_layout)
    LinearLayout recordTimerIcon;
    @BindView(R.id.record_timer_layout)
    RelativeLayout recordTimerLayout;

    @BindView(R.id.play_timer_textView)
    TextView playTimerTv;
    @BindView(R.id.play_timer_icon_layout)
    LinearLayout playTimerIcon;
    @BindView(R.id.play_timer_layout)
    RelativeLayout playTimerLayout;

    @BindView(R.id.uvMeter)
    VUMeter uvMeter;

    @BindView(R.id.sb_setSys_media)
    SeekBar mSeekMedia;

    @BindView(R.id.start_and_stop_record_audio_button)
    Button startAndStopRecordAudioBtn;
    @BindView(R.id.start_and_stop_play_audio_button)
    Button startAndStopPlayAudioBtn;
    @BindView(R.id.test_auto_record_audio_button)
    Button testAutoRecordAudioBtn;
    @BindView(R.id.test_record_with_play_audio_button)
    Button testRecordWithPlayAudioBtn;
    @BindView(R.id.test_play_audio_button)
    Button testPlayAudioBtn;
    @BindView(R.id.audio_test_info_textView)
    TextView infoTv;


    /**
     * 定义一个变量用于表示当前正在执行的功能按钮id
     */
    private int currentRunButtonId = CURRENT_RUN_BUTTON_ID_NONE;

    private int curMediaProgress;

    private ResultDialog resultDialog;

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_test_audio;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_3, getResources().getString(R.string.microphone), getContext());            //设置弹窗发送的事件——麦克风测试

        //初始化音频管理器
        mPresenter.initAudioManager();

        startAndStopRecordAudioBtn.setTag("close");
        startAndStopPlayAudioBtn.setTag("close");
        testAutoRecordAudioBtn.setTag("close");
        testRecordWithPlayAudioBtn.setTag("close");
        testPlayAudioBtn.setTag("close");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //移除所有Handler事件
        uiHandler.removeMessages(MSG_REFRESH_RECORD_TIMER_TIME);
        uiHandler.removeMessages(MSG_REFRESH_PLAY_TIMER_TIME);
    }

    @OnClick({R.id.start_and_stop_record_audio_button, R.id.start_and_stop_play_audio_button, R.id.test_auto_record_audio_button,
            R.id.test_record_with_play_audio_button, R.id.test_play_audio_button})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.start_and_stop_record_audio_button: {             //录音
                if (checkButtonCanRun(R.id.start_and_stop_record_audio_button)) {
                    if (startAndStopRecordAudioBtn.getTag().equals("close")) {
                        mPresenter.startRecord(true);
                        startAndStopRecordAudioBtn.setTag("open");
                        startAndStopRecordAudioBtn.setText(getStrById(R.string.stop_record_audio_button));
                        //更新标记位，判定该功能进入运作模式
                        setCurrentRunButtonId(R.id.start_and_stop_record_audio_button);
                    } else {
                        mPresenter.stopRecord();
                        startAndStopRecordAudioBtn.setTag("close");
                        startAndStopRecordAudioBtn.setText(getStrById(R.string.start_record_audio_button));
                        //更新标记位，判定该功能退出运作模式
                        setCurrentRunButtonId(CURRENT_RUN_BUTTON_ID_NONE);
                    }
                }
                break;
            }
            case R.id.start_and_stop_play_audio_button: {               //播放录音
                if (checkButtonCanRun(R.id.start_and_stop_play_audio_button)) {
                    openOrClosePlayRecord(false);
                }
                break;
            }
            case R.id.test_auto_record_audio_button: {                  //循环录音测试
                if (checkButtonCanRun(R.id.test_auto_record_audio_button)) {
                    if (testAutoRecordAudioBtn.getTag().equals("close")) {
                        mPresenter.startAutoCycleRecordTest();
                        testAutoRecordAudioBtn.setTag("open");
                        testAutoRecordAudioBtn.setText(getStrById(R.string.stop_test_auto_record_audio_button));
                        //更新标记位，判定该功能进入运作模式
                        setCurrentRunButtonId(R.id.test_auto_record_audio_button);
                    } else {
                        mPresenter.stopAutoCycleRecordTest();
                        testAutoRecordAudioBtn.setTag("close");
                        testAutoRecordAudioBtn.setText(getStrById(R.string.start_test_auto_record_audio_button));
                        //更新标记位，判定该功能退出运作模式
                        setCurrentRunButtonId(CURRENT_RUN_BUTTON_ID_NONE);
                    }
                }
                break;
            }
            case R.id.test_record_with_play_audio_button: {
                if (checkButtonCanRun(R.id.test_record_with_play_audio_button)) {
                    if (testRecordWithPlayAudioBtn.getTag().equals("close")) {
                        mPresenter.startRecordAudioWithPlayMusic();
                        testRecordWithPlayAudioBtn.setTag("open");
                        testRecordWithPlayAudioBtn.setText(getStrById(R.string.stop_test_record_with_play_audio_button));
                        //更新标记位，判定该功能进入运作模式
                        setCurrentRunButtonId(R.id.test_record_with_play_audio_button);
                    } else {
                        mPresenter.stopRecordAudioWithPlayMusic();
                        testRecordWithPlayAudioBtn.setTag("close");
                        testRecordWithPlayAudioBtn.setText(getStrById(R.string.start_test_record_with_play_audio_button));
                        //更新标记位，判定该功能退出运作模式
                        setCurrentRunButtonId(CURRENT_RUN_BUTTON_ID_NONE);
                    }
                }
                break;
            }
            case R.id.test_play_audio_button: {
                if (checkButtonCanRun(R.id.test_play_audio_button)) {
                    if (testPlayAudioBtn.getTag().equals("close")) {
                        mPresenter.startPlayTestMusic(true);
                        testPlayAudioBtn.setTag("open");
                        testPlayAudioBtn.setText(getStrById(R.string.stop_test_play_audio_button));
                        //更新标记位，判定该功能进入运作模式
                        setCurrentRunButtonId(R.id.test_play_audio_button);
                    } else {
                        mPresenter.stopPlayTestMusic();
                        testPlayAudioBtn.setTag("close");
                        testPlayAudioBtn.setText(getStrById(R.string.start_test_play_audio_button));
                        //更新标记位，判定该功能退出运作模式
                        setCurrentRunButtonId(CURRENT_RUN_BUTTON_ID_NONE);
                    }
                }
                break;
            }
        }
    }

    /**
     * 定义一个方法用于 检测点击的功能按钮是否允许被执行
     *
     * @param clickButtonId 当前点击的按钮id
     * @return 是否允许执行
     */
    private boolean checkButtonCanRun(int clickButtonId) {
        if (currentRunButtonId == CURRENT_RUN_BUTTON_ID_NONE) {  //当前没有功能按钮在执行，直接允许执行
            return true;
        } else {         //当前已有功能按钮在执行
            if (clickButtonId == currentRunButtonId) {       //如果当前点击的按钮 为 currentRunButtonId 中当前正在执行功能的按钮，则允许执行
                return true;
            } else {
                //根据currentRunButtonId 当前执行的功能做出相应提示
                String functionName = "正在运行的功能";
                switch (currentRunButtonId) {
                    case R.id.start_and_stop_record_audio_button: {             //录音
                        functionName = "录音";
                        break;
                    }
                    case R.id.start_and_stop_play_audio_button: {               //播放录音
                        functionName = "播放录音";
                        break;
                    }
                    case R.id.test_auto_record_audio_button: {                  //循环录音测试
                        functionName = "循环录音测试";
                        break;
                    }
                    case R.id.test_record_with_play_audio_button: {             //同时录音放音测试
                        functionName = "同时录音放音测试";
                        break;
                    }
                    case R.id.test_play_audio_button: {                         //放音测试
                        functionName = "放音测试";
                        break;
                    }
                }
                showMsg("请先停止 " + functionName + " 功能后再执行");
                return false;
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (resultDialog.isShowing()){
            resultDialog.dispatchKeyEvent(event);
        }
        if (event.getKeyCode() == Key.Convert.KEYCODE_7) {
            //降低音量
            if (curMediaProgress > 0) {
                curMediaProgress--;
                mSeekMedia.setProgress(curMediaProgress);
                mPresenter.updateMusicVolume(curMediaProgress);
                mPresenter.playRing();
            }
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_9) {
            //提高音量
            if (curMediaProgress < 15) {
                curMediaProgress++;
                mSeekMedia.setProgress(curMediaProgress);
                mPresenter.updateMusicVolume(curMediaProgress);
                mPresenter.playRing();
            }
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_1) {    //录音
            startAndStopRecordAudioBtn.performClick();
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_2){     //播放录音
            startAndStopPlayAudioBtn.performClick();
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_3){     //循环录音测试
            testAutoRecordAudioBtn.performClick();
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_4){     //同时录音放音测试
            testRecordWithPlayAudioBtn.performClick();
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_5){     //放音测试
            testPlayAudioBtn.performClick();
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void openOrClosePlayRecord(boolean isOnlyChangeUi) {
        if (startAndStopPlayAudioBtn.getTag().equals("close")) {
            if (!isOnlyChangeUi) {
                mPresenter.startPlayRecord(true);
            }
            startAndStopPlayAudioBtn.setTag("open");
            startAndStopPlayAudioBtn.setText(getStrById(R.string.stop_play_audio_button));
            //更新标记位，判定该功能进入运作模式
            setCurrentRunButtonId(R.id.start_and_stop_play_audio_button);
        } else {
            if (!isOnlyChangeUi) {
                mPresenter.stopPlayRecord();
            }
            startAndStopPlayAudioBtn.setTag("close");
            startAndStopPlayAudioBtn.setText(getStrById(R.string.start_play_audio_button));
            //更新标记位，判定该功能退出运作模式
            setCurrentRunButtonId(CURRENT_RUN_BUTTON_ID_NONE);
        }
    }

    private final Handler uiHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REFRESH_RECORD_TIMER_TIME: {            //刷新录音时的时长
                    boolean isNeedHidePlayTimer = (boolean) msg.obj;
                    long currentRecordLengthTime = MediaRecordClient.getInstance().getCurrentRecordLengthTime();
                    String timeStr = String.format(timerFormat, currentRecordLengthTime / 60, currentRecordLengthTime % 60);
                    Log.i(TAG, "handleMessage: 时间：" + timeStr + " | " + currentRecordLengthTime + " 是否需要隐藏播放计时器UI： " + isNeedHidePlayTimer);

                    if (isNeedHidePlayTimer) {
                        //隐藏播放计时器UI
                        playTimerLayout.setVisibility(View.GONE);
                    }

                    //显示录音计时器UI
                    recordTimerTv.setText(timeStr);
                    recordTimerIcon.setVisibility(View.VISIBLE);
                    recordTimerLayout.setVisibility(View.VISIBLE);

                    //延时1秒后再次执行
                    uiHandler.sendMessageDelayed(uiHandler.obtainMessage(MSG_REFRESH_RECORD_TIMER_TIME, isNeedHidePlayTimer),
                            REFRESH_DELAY_TIME);
                    break;
                }

                case MSG_REFRESH_PLAY_TIMER_TIME: {
                    boolean isNeedHideRecordTimer = (boolean) msg.obj;

                    int duration = mPresenter.getMediaPlayerClient().getDuration() / 1000;
                    int currentPosition = mPresenter.getMediaPlayerClient().getCurrentPosition() / 1000;
                    String timeStr = String.format(timerFormat, currentPosition / 60, currentPosition % 60) + " / " +
                            String.format(timerFormat, duration / 60, duration % 60);

                    if (isNeedHideRecordTimer) {
                        //隐藏录音计时器UI
                        recordTimerLayout.setVisibility(View.GONE);
                    }
                    //显示播放计时器UI
                    playTimerTv.setText(timeStr);
                    playTimerIcon.setVisibility(View.VISIBLE);
                    playTimerLayout.setVisibility(View.VISIBLE);

                    //延时1秒后再次执行
                    uiHandler.sendMessageDelayed(uiHandler.obtainMessage(MSG_REFRESH_PLAY_TIMER_TIME, isNeedHideRecordTimer),
                            REFRESH_DELAY_TIME);
                    break;
                }
            }
            return false;
        }
    });

    private SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser){
                curMediaProgress = progress;
                mPresenter.updateMusicVolume(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mPresenter.playRing();
        }

    };

    public int getCurrentRunButtonId() {
        return currentRunButtonId;
    }

    public void setCurrentRunButtonId(int currentRunButtonId) {
        this.currentRunButtonId = currentRunButtonId;
    }

    @Override
    public void refreshVUMeter() {
        uvMeter.refreshUi();
    }

    @Override
    public void startTimerRefreshForRecord(boolean isNeedHidePlayTimer) {
        //1秒后开始执行刷新
        uiHandler.sendMessage(uiHandler.obtainMessage(MSG_REFRESH_RECORD_TIMER_TIME, isNeedHidePlayTimer));
    }

    @Override
    public void startTimerRefreshForPlay(boolean isNeedHideRecordTimer) {
        //开始执行刷新
        uiHandler.sendMessage(uiHandler.obtainMessage(MSG_REFRESH_PLAY_TIMER_TIME, isNeedHideRecordTimer));

    }

    @Override
    public void resetTimer() {
        //移除所有Handler计时刷新事件
        uiHandler.removeMessages(MSG_REFRESH_RECORD_TIMER_TIME);
        uiHandler.removeMessages(MSG_REFRESH_PLAY_TIMER_TIME);

        //只保留录音计时器UI
        recordTimerTv.setText("00:00");
        recordTimerIcon.setVisibility(View.GONE);
        recordTimerLayout.setVisibility(View.VISIBLE);

        //隐藏播放计时器UI
        playTimerTv.setText("00:00 / 00:00");
        playTimerIcon.setVisibility(View.GONE);
        playTimerLayout.setVisibility(View.GONE);
    }

    @Override
    public void refreshInfoText(String content) {
        if (infoTv != null) {
            infoTv.setText(content);
        }
    }

    @Override
    public void initVolumeSeekBar(int currentMusicVolume, int maxStreamMusicVolume) {
        Log.e(TAG, "initVolumeSeekBar: 当前设备的媒体音量为： " + currentMusicVolume + " 最大音量为： " + maxStreamMusicVolume);
        curMediaProgress = currentMusicVolume;
        mSeekMedia.setProgress(currentMusicVolume);
        mSeekMedia.setMax(maxStreamMusicVolume);
        mSeekMedia.setOnSeekBarChangeListener(mSeekBarChangeListener);
    }

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        resultDialog.show();
    }

    @Override
    protected TestAudioPresenter createPresenter() {
        return new TestAudioPresenter(getActivity());
    }
}
